import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.wtwd.campus.entity.BaseEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author zdl
 * @Description
 * @create 2020-12-31 11:22
 */
public class GeneratorCodeConfig {
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (ipt != null && !"".equals(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置

        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/campus-ManagerBackStage2/src/main/java");
        gc.setAuthor("mjy");
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setDateType(DateType.ONLY_DATE); //定义生成的实体类中日期类型
        gc.setServiceName("%sService");
        gc.setOpen(false);
        gc.setBaseColumnList(true);  //生成基本的SQL
        gc.setFileOverride(true);
        boolean onlyOverrideEntity = "1".equals(scanner("是-否(1-0),仅覆盖Entity"));
        gc.setFileOverride(onlyOverrideEntity);// 覆盖已存在文件

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/campus_card_local?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));
//        pc.setParent("com.wtwd.campus");
        pc.setParent("");
        pc.setEntity("com.wtwd.campus.entity");
        pc.setMapper("com.wtwd.campus.dao");
        pc.setService("com.wtwd.campus.service");
        pc.setServiceImpl("com.wtwd.campus.service.impl");
        pc.setController("com.wtwd.campus.controller");
        mpg.setPackageInfo(pc);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        if (onlyOverrideEntity) {
            templateConfig.setService(null);
            templateConfig.setController(null);
            templateConfig.setServiceImpl(null);
            templateConfig.setService(null);
            templateConfig.setMapper(null);
            cfg.setFileCreate((configBuilder, fileType, filePath) -> {
                //如果是Entity则直接返回true表示写文件
                if (fileType == FileType.ENTITY) {
                    return true;
                }
                //全局配置的fileOverride为true才写文件
                return false;
            });
            mpg.setCfg(cfg);
        }
        templateConfig.setXml(null);
        // 自定义配置

        //xml 自定义配置
        if (!onlyOverrideEntity) {
            // 模板引擎是 freemarker
            //String templatePath = "/templates/mapper.xml.ftl";
            // 模板引擎是 velocity
            String templatePath = "/templates/mapper.xml.vm";
            // 自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义xml输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                    return projectPath + "/campus-ManagerBackStage2/src/main/resources/mapper/" + pc.getModuleName()
                            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
        }
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        boolean isEnableConfig = "1".equals(scanner("是否开启配置"));
        if (isEnableConfig) {
            boolean isExtendEntity = "1".equals(scanner("是否继承父类实体"));
            if (isExtendEntity) {
                strategy.setSuperEntityClass(BaseEntity.class);
                // 写于父类中的公共字段
                strategy.setSuperEntityColumns("create_time", "update_time");
            }
            if ("1".equals(scanner("是否,生成swagger注解"))) {
                gc.setSwagger2(true);
            }
        }
        strategy.setRestControllerStyle(true);

        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setGlobalConfig(gc);
        mpg.setStrategy(strategy);
        mpg.execute();
    }
}
